package com.callbell.cas.action;

import javax.sql.DataSource;

import org.jasig.cas.authentication.principal.Credentials;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
import org.jasig.cas.ticket.TicketException;
import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.webflow.execution.RequestContext;

import com.callbell.cas.context.CaptchaConst;
import com.callbell.cas.context.CaptchaContext;
import com.callbell.cas.exception.TicketCaptchaException;
import com.google.code.kaptcha.Constants;

@SuppressWarnings("deprecation")
public class AuthenticationEntryAction {

	private SimpleJdbcTemplate jdbcTemplate;

	private DataSource dataSource;

	private String querySql;

	public String getQuerySql() {
		return querySql;
	}

	public void setQuerySql(String querySql) {
		this.querySql = querySql;
	}

	/**
	 * Method to set the datasource and generate a JdbcTemplate.
	 * 
	 * @param dataSource
	 *            the datasource to use.
	 */
	public final void setDataSource(final DataSource dataSource) {
		this.jdbcTemplate = new SimpleJdbcTemplate(dataSource);
		this.dataSource = dataSource;
	}

	/**
	 * Method to return the jdbcTemplate
	 * 
	 * @return a fully created JdbcTemplate.
	 */
	protected final SimpleJdbcTemplate getJdbcTemplate() {
		return this.jdbcTemplate;
	}

	protected final DataSource getDataSource() {
		return this.dataSource;
	}

	/**
	 * 
	 * 验证码检查 <br>
	 * 
	 * <pre>
	 * 方法checkCaptcha的详细说明 <br>
	 * 编写者：xlh
	 * 创建时间：2014-2-17 下午4:24:40
	 * </pre>
	 * 
	 * @param 参数名
	 *            说明
	 * @return String 说明
	 * @throws 异常类型
	 *             说明
	 */
	public final String checkCaptcha(final RequestContext context, final Credentials credentials, final MessageContext messageContext) throws Exception {
		UsernamePasswordCredentials up = null;
		String userName = "";
		try {
			up = (UsernamePasswordCredentials) credentials;
			userName = up.getUsername();
		} catch (Exception e) {

		}
		Integer attemptLoginCount = CaptchaContext.getAttemptLoginCount(userName);
		context.getExternalContext().getSessionMap().put("loginName", userName);
		// 如果用户还未登录失败，或者没超过设置的失败次数，直接返回
		if (attemptLoginCount == null || attemptLoginCount < CaptchaConst.MAX_ERROR_SHOW_CAPTCHA - 1) {
			return null;
		}
		attemptLoginCount = ((Integer) attemptLoginCount) + 1; // 记录尝试登录次数
		// 大于设置的最大尝试次数之后将会锁定账户。
		if ((Integer) attemptLoginCount >= CaptchaConst.MAX_ATTEMP_LOGIN_COUNT) { // 大于设置的最大登录尝试次数, 执行数据库账户锁定
			getJdbcTemplate().update("update user u set u.status = 0 where u.account = ?", userName);
		}
		Integer remainLoginCount = new Integer(CaptchaConst.MAX_ATTEMP_LOGIN_COUNT - attemptLoginCount);
		// 是否要显示验证码
		if (CaptchaConst.MAX_ATTEMP_LOGIN_COUNT > 0 && (Integer) attemptLoginCount >= CaptchaConst.MAX_ERROR_SHOW_CAPTCHA) {
			context.getFlowScope().put("remainLoginCountForShow", remainLoginCount);
		}

		String capText = (String) context.getExternalContext().getSessionMap().get(Constants.KAPTCHA_SESSION_KEY);
		if (capText != null) {
			if (capText.equalsIgnoreCase(up.getCaptcha())) { // 比较验证码
				context.getExternalContext().getSessionMap().remove(Constants.KAPTCHA_SESSION_KEY);
			} else { // 验证码无效
				TicketCaptchaException e = new TicketCaptchaException(TicketCaptchaException.INVALID_CAPTCHA);
				populateErrorsInstance(e, context.getMessageContext());
				return "error";
			}
		}
		return null;
	}

	private void populateErrorsInstance(final TicketException e, final MessageContext messageContext) {
		try {
			messageContext.addMessage(new MessageBuilder().error().code(e.getCode()).defaultText(e.getCode()).build());
		} catch (final Exception fe) {
			fe.printStackTrace();
		}
	}
}